//
//  CYHSubjectDrawVC.m
//  Cat
//
//  Created by dllo on 15/12/2.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "CYHSubjectDrawVC.h"
#import <ACEDrawingView.h>
#import <CoreImage/CoreImage.h>
@interface CYHSubjectDrawVC ()<ACEDrawingViewDelegate>

@property (nonatomic, strong) UIView *leftView;
@property (nonatomic, strong) ACEDrawingView *drawView;
@property (nonatomic, strong) ACEDrawingView *mengbanView;

@property (nonatomic, strong) UIButton *undoButton;
@property (nonatomic, strong) UIButton *redoButton;
@property (nonatomic, strong) UIButton *clearButton;

@property (nonatomic, strong) UISlider *lineAlphaSlider;
@property (nonatomic, strong) UISlider *lineWidthSlider;

@property (nonatomic, strong) UISegmentedControl *seg;
@property (nonatomic, strong) UIImageView *backImageView;

@end

@implementation CYHSubjectDrawVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // 背景View
    self.backImageView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 40, VIEW_WIDTH - 50, VIEW_HEIGHT - 100)];
    [self.backImageView sd_setImageWithURL:[NSURL URLWithString:self.PicUrl]];
   
    [self.view addSubview:self.backImageView];
    
    self.backImageView.image = [self grayscaleImage:self.backImageView.image];
    // 画图View
    self.drawView = [[ACEDrawingView alloc] initWithFrame:CGRectMake(50, 40, VIEW_WIDTH - 50, VIEW_HEIGHT - 100)];
    self.drawView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.drawView];
    self.drawView.delegate = self;
    // 笔种类
    self.drawView.drawTool = ACEDrawingToolTypePen;
    
    // 层次
    [self.view bringSubviewToFront:self.drawView];
    
    
    // 菜单按钮
    UIButton *menuButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:menuButton];
    [menuButton setImage:[UIImage imageNamed:@"resizeApi.php@2x.png"] forState:UIControlStateNormal];
    menuButton.frame = CGRectMake(0, VIEW_HEIGHT / 3, 30, 30);
    [menuButton addTarget:self action:@selector(menuButton:) forControlEvents:UIControlEventTouchUpInside];
    
    // 侧拉View
    self.leftView = [[UIView alloc] initWithFrame:CGRectMake(-self.view.frame.size.width / 2, 0, self.view.frame.size.width / 2, self.view.frame.size.height)];
    [self.view addSubview:self.leftView];
    self.leftView.backgroundColor = [UIColor colorWithRed:.0 green:.8 blue:.9 alpha:.2];
    
    // 蒙版
    self.mengbanView = [[ACEDrawingView alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2, 0, self.view.frame.size.width / 2, self.view.frame.size.height)];
    [self.view addSubview:self.mengbanView];
    self.mengbanView.hidden = YES;
    
    
    //毛玻璃
    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    effectView.frame = CGRectMake(0, 0, self.view.frame.size.width / 2, self.view.frame.size.height);
    
    [self.view bringSubviewToFront:self.leftView];
    [self.leftView addSubview:effectView];
    effectView.alpha = 1;
    
    // 调节粗细
    self.lineWidthSlider = [[UISlider alloc] initWithFrame:CGRectMake(20, VIEW_WIDTH / 2 - 50, VIEW_HEIGHT / 4, 20)];
    [self.leftView addSubview:self.lineWidthSlider];
    // 粗细
    self.lineWidthSlider.value = self.drawView.lineWidth;
    self.lineWidthSlider.minimumValue = 1;
    self.lineWidthSlider.maximumValue = 20;
    [self.lineWidthSlider addTarget:self action:@selector(lineSlider:) forControlEvents:UIControlEventValueChanged];
    
    // 调节透明度
    self.lineAlphaSlider = [[UISlider alloc] initWithFrame:CGRectMake(20, VIEW_WIDTH / 2, VIEW_HEIGHT / 4, 20)];
    [self.leftView addSubview:self.lineAlphaSlider];
    // 透明度
    self.lineAlphaSlider.value = self.drawView.lineAlpha;
    self.lineAlphaSlider.minimumValue = 0;
    self.lineAlphaSlider.maximumValue = 1;
    [self.lineAlphaSlider addTarget:self action:@selector(lineAlphaSlider:) forControlEvents:UIControlEventValueChanged];
    
    // label
    UILabel *widthLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, VIEW_WIDTH / 2 - 80, VIEW_HEIGHT / 4, 20)];
    widthLabel.text = @"调节粗细";
    [self.leftView addSubview:widthLabel];
    
    UILabel *AlphaLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, VIEW_WIDTH / 2 - 20, VIEW_HEIGHT / 4, 20)];
    AlphaLabel.text = @"透明度";
    [self.leftView addSubview:AlphaLabel];
    
    // 确定
    UIButton *OKButton = [UIButton buttonWithType:UIButtonTypeSystem];
    OKButton.frame = CGRectMake(50, VIEW_HEIGHT / 3 * 2, VIEW_WIDTH / 4, 50);
    [self.leftView addSubview:OKButton];
    [OKButton setTitle:@"确定" forState:UIControlStateNormal];
    [OKButton addTarget:self action:@selector(swipeAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    // 左侧View
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, VIEW_HEIGHT - (VIEW_HEIGHT / 3), 30, VIEW_HEIGHT / 3)];
    [self.view addSubview:bottomView];
    
    // 撤销
    self.undoButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.undoButton setTitle:@"撤销" forState:UIControlStateNormal];
    self.undoButton.frame = CGRectMake(0, 20, 30, 30);
    [bottomView addSubview:self.undoButton];
    [self.undoButton addTarget:self action:@selector(undoAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.undoButton setImage:[UIImage imageNamed:@"undo.png"] forState:UIControlStateNormal];
    
    // 还原
    self.redoButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.redoButton setTitle:@"还原" forState:UIControlStateNormal];
    self.redoButton.frame = CGRectMake(0,  60, 30, 30);
    [bottomView addSubview:self.redoButton];
    [self.redoButton addTarget:self action:@selector(redoAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.redoButton setImage:[UIImage imageNamed:@"iconfont-huanyuan.png"] forState:UIControlStateNormal];
    
    // 清空
    self.clearButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.clearButton setTitle:@"清空" forState:UIControlStateNormal];
    self.clearButton.frame = CGRectMake(0, 100, 30, 30);
    [bottomView addSubview:self.clearButton];
    [self.clearButton addTarget:self action:@selector(clearAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.clearButton setImage:[UIImage imageNamed:@"iconfont-qingchu.png"] forState:UIControlStateNormal];
    
    // 颜色
    self.seg = [[UISegmentedControl alloc] initWithItems:@[@"黑", @"红", @"绿", @"蓝"]];
    self.seg.frame = CGRectMake(0, VIEW_HEIGHT / 2, VIEW_WIDTH / 2, 20);
    [self.leftView addSubview:self.seg];
    [self.seg addTarget:self action:@selector(segAction:) forControlEvents:UIControlEventValueChanged];
    
    // 保存按钮
    UIButton *saveButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:saveButton];
    saveButton.frame = CGRectMake( -30, self.view.frame.size.height - VIEW_WIDTH / 4, VIEW_WIDTH / 3, VIEW_WIDTH / 3);
    saveButton.layer.cornerRadius = VIEW_WIDTH / 6;
    saveButton.layer.masksToBounds = YES;
    saveButton.tag = 9999;
    [self.view addSubview:saveButton];
    [saveButton setImage:[UIImage imageNamed:@"save.png"] forState:UIControlStateNormal];
    [saveButton addTarget:self action:@selector(saveAction:) forControlEvents:UIControlEventTouchUpInside];
    
    // 隐藏imageView
    UIButton *hiddenButton = [UIButton buttonWithType:UIButtonTypeCustom];
    hiddenButton.frame = CGRectMake(0, VIEW_HEIGHT / 3 + 50, 30, 30);
    [self.view addSubview:hiddenButton];
    [hiddenButton addTarget:self action:@selector(hiddenAction:) forControlEvents:UIControlEventTouchUpInside];
    [hiddenButton setImage:[UIImage imageNamed:@"eyesese.png"] forState:UIControlStateNormal];
    
    self.backImageView.hidden = NO;
}

// 还原
- (void)redoAction:(UIButton *)button {
    [self.drawView redoLatestStep];
    [self updateButtonStatus];
}

// 撤销
- (void)undoAction:(UIButton *)button {
    [self.drawView undoLatestStep];
    [self updateButtonStatus];
}

// 清空
- (void)clearAction:(UIButton *)button {
    [self.drawView clear];
    [self updateButtonStatus];
}

// 调节粗细
- (void)lineSlider:(UISlider *)slider {
    self.drawView.lineWidth = slider.value;
    self.mengbanView.lineWidth = slider.value;
}

// 调节透明度
- (void)lineAlphaSlider:(UISlider *)slider {
    self.drawView.lineAlpha = slider.value;
    self.mengbanView.lineAlpha = slider.value;
}

- (void)hiddenAction:(UIButton *)button {
    self.backImageView.hidden = !self.backImageView.hidden;
}

// 画笔颜色
- (void)segAction:(UISegmentedControl *)seg {
    switch (seg.selectedSegmentIndex) {
        case 0:
            self.drawView.lineColor = [UIColor blackColor];
            self.mengbanView.lineColor = [UIColor blackColor];
            break;
            
        case 1:
            self.drawView.lineColor = [UIColor redColor];
            self.mengbanView.lineColor = [UIColor redColor];
            break;
            
        case 2:
            self.drawView.lineColor = [UIColor greenColor];
            self.mengbanView.lineColor = [UIColor greenColor];
            break;
            
        case 3:
            self.drawView.lineColor = [UIColor blueColor];
            self.mengbanView.lineColor = [UIColor blueColor];
            break;
        default:
            break;
    }
    
}

// 开始画画
- (void)updateButtonStatus
{
    self.undoButton.enabled = [self.drawView canUndo];
    self.redoButton.enabled = [self.drawView canRedo];
}

- (void)drawingView:(ACEDrawingView *)view didEndDrawUsingTool:(id<ACEDrawingTool>)tool;
{
    [self updateButtonStatus];
}



// 点击隐藏菜单
- (void)swipeAction:(UIButton *)swipe {
    
    // 左划
    CATransition *animation = [CATransition animation];
    animation.duration = 0.3f;
    animation.timingFunction=UIViewAnimationCurveEaseInOut;
    animation.type = kCATransitionPush;
    animation.subtype = kCATransitionFromRight;
    [self.leftView.layer addAnimation:animation forKey:@"animation"];
    
    [self.leftView setTransform:CGAffineTransformMakeTranslation(-self.view.frame.size.width / 2, 0)];
    
    // 蒙版隐藏
    self.mengbanView.hidden = YES;
    [self.mengbanView clear];
}

// 点击出菜单
- (void)menuButton:(UIButton *)button {
    
    CATransition *animation = [CATransition animation];
    animation.duration = 0.3f;
    animation.timingFunction = UIViewAnimationCurveEaseInOut;
    // 改编动画样式
    animation.type = kCATransitionPush;
    // animation.type = @"";
    animation.subtype = kCATransitionFromLeft;
    [self.leftView.layer addAnimation:animation forKey:@"animation"];

    self.leftView.transform = CGAffineTransformMakeTranslation(self.view.frame.size.width / 2, 0);
    
    
    // 蒙版出现
    self.mengbanView.hidden = NO;
}

// 保存本地
- (void)saveAction:(UIButton *)button {
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"保存" message:@"是否保存" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *OKAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        UIImageWriteToSavedPhotosAlbum(self.drawView.image, self, @selector(imageToPhotosAlbum:Error:contextinfo:), nil);
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
        
        [self.navigationController popViewControllerAnimated:YES];
        self.leftView.hidden = YES;
    }];
    
    [alert addAction:cancelAction];
    [alert addAction:OKAction];
    
    [self presentViewController:alert animated:YES completion:nil];
    
    
}

- (void)imageToPhotosAlbum:(UIImage *)image Error:(NSError *)error contextinfo:(NSString *)info{
    
}



- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    UIButton *saveButton = (UIButton *)[self.view viewWithTag:9999];
    [self saveAction:saveButton];
    
    self.navigationController.navigationBarHidden = NO;
    self.tabBarController.tabBar.hidden = NO;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    self.leftView.hidden = NO;
}

- (UIImage *) grayscaleImage: (UIImage *) image
{
    CGSize size = image.size;
    CGRect rect = CGRectMake(0.0f, 0.0f, image.size.width,
                             image.size.height);
    // Create a mono/gray color space
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
    CGContextRef context = CGBitmapContextCreate(nil, size.width,
                                                 size.height, 8, 0, colorSpace, kCGImageAlphaNone);
    CGColorSpaceRelease(colorSpace);
    // Draw the image into the grayscale context
    CGContextDrawImage(context, rect, [image CGImage]);
    CGImageRef grayscale = CGBitmapContextCreateImage(context);
    CGContextRelease(context);
    // Recover the image
    UIImage *img = [UIImage imageWithCGImage:grayscale];
    CFRelease(grayscale);
    return img;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
